package devicedbgui;

import devicedbgui.data.Build;
import devicedbgui.data.Exe;
import devicedbgui.data.ExeDAO;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/** Displays all exe records associated with the current build */
public class ExePanel extends javax.swing.JPanel {
    
    /** Reference to GUI class for accessing its variables */
     public GUI gui;
    Hashtable<Integer, Exe> htExe = new Hashtable<Integer, Exe>();
    
    /** Constructor creates all components belonging to panel */   
    public ExePanel() {
        initComponents();
    }
    /** Displays error messages */
 public void showError(JFrame parent, String error)
    {
        JOptionPane.showMessageDialog(parent, error);
    }
    /** Displays exes  associated with build */
    public void showExes(GUI gui, Build build)
    {
        this.gui = gui;
      //  this.setTitle(build.idBuild + " - Exes");
        ExeDAO dd = new ExeDAO(gui.connection);
        try {
            ArrayList<Exe> records = dd.selectByBuild(build.idBuild);
            DefaultTableModel model = (DefaultTableModel)tblExe.getModel();
            model.getDataVector().clear();
            int index = 0;   
            htExe.clear();
            for (Exe item : records){ 
                htExe.put(new Integer(index++), item);
                model.addRow(new Object[]{item.idexe, item.description, item.Build_idBuild});
            }
             
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
     }
    /** Displays all exes available in database */
    public void showAll(GUI gui)
    {
        this.gui = gui;
      
        ExeDAO dd = new ExeDAO(gui.connection);
        try {
            ArrayList<Exe> records = dd.selectAll();
            DefaultTableModel model = (DefaultTableModel)tblExe.getModel();
            model.getDataVector().clear();
            int index = 0;   
            htExe.clear();
            for (Exe item : records){ 
                htExe.put(new Integer(index++), item);
                model.addRow(new Object[]{item.idexe, item.description, item.Build_idBuild});
            }
            
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
     }
    /** Refreshes display of list of exes in database */
    public void update()
    {
        ExeDAO dd = new ExeDAO(gui.connection);
        try {
            ArrayList<Exe> records = dd.selectByBuild(Integer.parseInt(gui.getBuildId()));
            DefaultTableModel model = (DefaultTableModel)tblExe.getModel();
            model.getDataVector().clear();
            int index = 0;   
            htExe.clear();
            for (Exe item : records){ 
                htExe.put(new Integer(index++), item);
                model.addRow(new Object[]{item.idexe, item.description, item.Build_idBuild});
            }
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblExe = new javax.swing.JTable(){    public Component prepareRenderer(TableCellRenderer renderer,
            int rowIndex, int vColIndex) {
            Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
            if (rowIndex % 2 == 0 && !tblExe.isRowSelected(rowIndex)) {
                c.setBackground(new Color(237, 242, 251));
            }
            else if (tblExe.isRowSelected(rowIndex)){c.setBackground(new Color(184, 207, 229));}
            else { c.setBackground(getBackground());}
            return c;
        }
    }
    ;
    btnViewTestCase = new javax.swing.JButton();
    btnAdd = new javax.swing.JButton();
    btnEdit = new javax.swing.JButton();
    btnDelete = new javax.swing.JButton();

    tblExe.setAutoCreateRowSorter(true);
    tblExe.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null}
        },
        new String [] {
            "Exe ID", "Description", "Build ID"
        }
    ) {
        boolean[] canEdit = new boolean [] {
            false, false, false
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    tblExe.setGridColor(new java.awt.Color(204, 204, 255));
    tblExe.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jScrollPane1.setViewportView(tblExe);

    btnViewTestCase.setText("View Test Case ");
    btnViewTestCase.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnViewTestCaseActionPerformed(evt);
        }
    });

    btnAdd.setText("Add");
    btnAdd.setMnemonic(KeyEvent.VK_D);
    btnAdd.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnAddActionPerformed(evt);
        }
    });

    btnEdit.setText("Edit");
    btnEdit.setMnemonic(KeyEvent.VK_I);
    btnEdit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnEditActionPerformed(evt);
        }
    });

    btnDelete.setText("Delete");
    btnDelete.setMnemonic(KeyEvent.VK_DELETE);
    btnDelete.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnDeleteActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnEdit)
                    .addComponent(btnAdd)
                    .addComponent(btnDelete))
                .addComponent(btnViewTestCase))
            .addContainerGap())
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAdd, btnDelete, btnEdit, btnViewTestCase});

    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(btnAdd)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnEdit)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnDelete)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnViewTestCase))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE))
            .addContainerGap())
    );
    }// </editor-fold>//GEN-END:initComponents
/** Shows all test cases run from selected exe */
private void btnViewTestCaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewTestCaseActionPerformed
int selectedIndex = tblExe.getSelectedRow();    
    if (selectedIndex == -1){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    Exe item = htExe.get(new Integer(selectedIndex));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    gui.setExeID(String.valueOf(item.idexe));
    TestCasePanel ts = new TestCasePanel();
    ts.showTestCases(gui, item);
    
    
    
   gui.tab.add(ts);
   gui.tab.setSelectedComponent(ts);
   gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("View Test Cases") );
   
}//GEN-LAST:event_btnViewTestCaseActionPerformed
/** Add new build for current build */
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
//if (gui.connection == null)
        //return;
    EditExeDlg dlg = new EditExeDlg(gui, null, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB){
        update();
    }
}//GEN-LAST:event_btnAddActionPerformed
/* Edit exe information */
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
int[] selected = tblExe.getSelectedRows();  
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    Exe item = htExe.get(new Integer(selected[0]));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    EditExeDlg dlg = new EditExeDlg(gui, item, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB){
        htExe.remove(new Integer(selected[0]));        
        htExe.put(new Integer(selected[0]), dlg.exe);
        update();
    }
}//GEN-LAST:event_btnEditActionPerformed
/* Delete selected exe record */
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
int[] selected = tblExe.getSelectedRows();  
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    // ask user if he surely wants to delete this record
    int option = JOptionPane.showConfirmDialog(gui.frame, "Are you sure to delete selected record(s)?", "Confirmation", JOptionPane.YES_NO_OPTION);
    if (option == JOptionPane.YES_OPTION)
    {        
        ExeDAO dd = new ExeDAO(gui.connection);
        try {
            for (int i = 0; i < selected.length; i++){
                Exe item = htExe.get(new Integer(selected[i]));   
                dd.delete(item.idexe);
                htExe.remove(new Integer(selected[i]));

            }           
            
        } catch (Exception e)
        {
            JOptionPane.showMessageDialog(gui.frame, e.toString());
        }
        update();
    }
}//GEN-LAST:event_btnDeleteActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnViewTestCase;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblExe;
    // End of variables declaration//GEN-END:variables

}
